
from collections import OrderedDict
from goods.models import GoodsChannel

def get_categories():
    #初始化存储容器
    categories = OrderedDict()
    #获取一级分类
    channels = GoodsChannel.objects.order_by('group_id','sequence')
    #对一级分类进行遍历
    for channel in channels:
        #获取group_id
        group_id = channel.group_id
        #判断group_id是否在存储容器，如果不在就初始化
        if group_id not in categories:
            categories[group_id] = {
                'channels':[],
                'sub_cats':[]
            }

        one = channel.category
        #为channels填充数据
        categories[group_id]['channels'].append({
            'id':one.id,
            'name':one.name,
            'url':channel.url
        })
        #为sub_cats填充数据
        for two in one.goodscategory_set.all():
            #初始化容器
            two.sub_cats = []
            #遍历获取
            for three in two.goodscategory_set.all():
                two.sub_cats.append(three)
            # 组织数据
            categories[group_id]['sub_cats'].append(two)

    return categories










































